package region

import (
	"context"
	"encoding/json"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/region/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/model/entity"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/cache"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {
	// return nil, gerror.NewCode(gcode.CodeNotImplemented)
	in := &v1.ListInput{}
	in.Country = req.Country
	out, err := service.Region().List(ctx, in)
	if err != nil {
		return nil, err
	}
	res = &v1.ListRes{}

	cc, _ := cache.NewCache()
	cache.InitCache(ctx, consts.InitialCacheKeys.RegionsKey, false)
	val, err := cc.Get(ctx, consts.InitialCacheKeys.RegionsKey)
	if err != nil {
		return nil, gerror.NewCode(consts.GetCachedRegionsFailed)
	}
	regionStr, ok := val.Val().(string)
	if !ok {
		return nil, gerror.NewCode(consts.ParseRegionCacheFailed)
	}
	regionMap := make(map[string]entity.Region, 0)
	json.Unmarshal([]byte(regionStr), &regionMap)

	regionTree := make(map[string]*v1.RegionTree, 0)
	for _, r := range out.Data {
		regionTree[r.Code] = &v1.RegionTree{
			Id:       r.Id,
			Code:     r.Code,
			Name:     r.Name,
			Level:    r.Level,
			Parent:   r.Parent,
			Children: []*v1.RegionTree{},
		}
	}
	// 构建树结构
	var roots []*v1.RegionTree
	for _, r := range out.Data {
		node := regionTree[r.Code]
		if r.Parent == "" {
			roots = append(roots, node)
		} else if parent, exists := regionTree[r.Parent]; exists {
			// 子节点
			parent.Children = append(parent.Children, node)
		}
	}
	res.Data = roots
	return res, nil
}
